<?php
/**
 * OA班级管理
 *
 * PHP version 5
 *
 * @package   YuDian
 * @author    lw
 * @copyright 2016 Shangyuanruige Inc.
 */
namespace app\controllers;

use alexgx\phpexcel\PhpExcel;
use app\models\Classinfo;
use app\models\Schools;
use app\models\sys\SysClassSubjects;
use app\models\sys\SysSubjects;
use app\models\timeplan\Syllabus;
use app\models\timeplan\Timeplans;
use app\models\timeplan\Timeplansets;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\RequestHelper;
use yii\data\Pagination;
use app\components\NoCsrfBehavior;

class ClassController extends CommonController
{
    public $navTabId;

    public function __construct($id, $module, $config = [])
    {
        $this->id = $id;
        $this->module = $module;

        parent::__construct($config);

        $this->navTabId = "classindex";

    }

    /**
     * behaviors
     *
     * @author Fee
     */
    public function behaviors()
    {
        return [
            'csrf' => [
                'class' => NoCsrfBehavior::className(),
                'controller' => $this,
                'actions' => [
                    'index','delete','delall','list'
                ]
            ]
        ];
    }

    /**
     * 显示列表页面
     *
     * @return html
     * @author Fee
     */
    public function actionIndex() {
        $this->checkAuth($this->id, $this->action->id);
        $school_id = Yii::$app->session["school_id"];
        $order_arr = array();
        $order_arr['type'] = SORT_DESC;
        $order_arr['year'] = SORT_ASC;

        //条件
        $where['school_id'] = $school_id;
        $search['type_id']  = '';
        if (!empty($_POST['type_id'])) {
            $where['type'] = $_POST['type_id'];
            $search['type_id'] = $_POST['type_id'];
        }
        if (!empty($_POST['school_id'])) {
            $where['school_id'] = $_POST['school_id'];
            $search['school_id'] = $_POST['school_id'];
        }
        if (!empty($_POST['orderField'])) {
            $orderField = $_POST['orderField'];

            if (isset ( $_POST['orderDirection'] )) {
                $orderDirection = $_POST['orderDirection'] == 'asc' ? SORT_ASC : SORT_DESC;
            } else {
                $orderDirection = SORT_DESC;
            }

            $order_arr[$orderField] = $orderDirection;
        } else {
            $orderField = "";
            $orderDirection = "";
        }

        if (!empty($_POST['numPerPage'])){
            $numPerPage = $_POST['numPerPage'];
        } else {
            $numPerPage = Yii::$app->params['oa_page_num'];
        }
        $query = Classinfo::find()->where($where);

        $count = $query->count();

        $pages = new Pagination(['totalCount' => $count, 'pageSize' => $numPerPage]);
        $list = $query->orderBy($order_arr)
            ->offset($pages->offset)
            ->limit($pages->limit)
            ->with('schools','plans','subject')
            ->select('*')
            ->asArray()
            ->all();
        return $this->render('index',[
            'list' => $list,
            'orderDirection' => $orderDirection,
            'orderField'     => $orderField,
            'totalCount'     => $count,
            'filters'        => $_POST,
            'numPerPage'     => $pages->limit,
            'currentPage'    => !empty($_POST['p'])?$_POST['p']:1,
            'search' =>$search,
            'schools' => Schools::getOptions($school_id),
            'type' =>$this->getState()
        ]);
    }
    /**
     * 新增
     */
    public function actionInserts()
    {
        $form = Yii::$app->request->post();
        //学校id
        $school_id = Yii::$app->session["school_id"];
        //条件
        $where['class_name'] =  $form['class_name'];
        $where['school_id'] =  $school_id;
        $where['year'] =  $form['year'];
        $where['type'] =  $form['type'];
        //班级是否存在
        $count = Classinfo::find()->where($where)->count();
        if ($count==0) {
            $data['class_name'] = $form['class_name'];
            $data['class_alias'] = $form['class_alias'];
            $data['school_id'] = (string)$school_id;
            $data['year'] = $form['year'];
            $data['type'] = $form['type'];
            $data['plan_id'] = $form['plan_id'];
            $data['remark'] = $form['remark'];
            //var_dump($data);exit;
            $model = new Classinfo();
            $result = $model->insertInfo($data);
            if ($result > 0) {
                $sub_model = new SysClassSubjects();
                foreach ($form['sub_id'] as $sub) {
                    $sub_data['class_id'] = $result;
                    $sub_data['sub_id'] = $sub;
                    $sub_model->insertInfo($sub_data);
                }
                $this->ajaxReturn(200, Yii::t('app', 'Add success'), $this->navTabId, 1);
            } else {
                $this->ajaxReturn(300, Yii::t('app', 'Add failed, please try again'));
            }
        } else {
            $this->ajaxReturn(300, Yii::t('app', 'Data already exists'));
        }
    }

    /**
     * 修改
     */
    public function actionUpdates()
    {
        $form = Yii::$app->request->post();
        //学校id
        $school_id = Yii::$app->session["school_id"];
        //条件
        $where['class_name'] =  $form['class_name'];
        $where['school_id'] =  $school_id;
        $where['year'] =  $form['year'];
        $where['type'] =  $form['type'];
        //班级是否存在
        $count = Classinfo::find()->where($where)->andWhere(['!=','class_id',$form['id']])->count();
        if ($count==0) {
            $data['class_name'] = $form['class_name'];
            $data['class_alias'] = $form['class_alias'];
            $data['year'] = $form['year'];
            $data['type'] = $form['type'];
            $data['plan_id'] = $form['plan_id'];
            $data['remark'] = $form['remark'];
            $model = new Classinfo();
            $result = $model->updateInfo($data, ['class_id' => $form['id']]);
            if ($result) {
                //获取科目
                $subject_list = SysClassSubjects::find()->where(['class_id' => $form['id']])->asArray()->all();
                $subject_ids = [];
                if ($subject_list) {
                    $subject_ids = ArrayHelper::getColumn($subject_list, 'sub_id');
                }
                $class_arr = $form['sub_id'];
                //判断是否改变
                $array_diff = array_diff($subject_ids,$class_arr);
                $array_diff1 = array_diff($class_arr,$subject_ids);
                $sub_model = new SysClassSubjects();
                if (!empty($array_diff) or !empty($array_diff1)) {
                    SysClassSubjects::deleteAll(['class_id' => $form['id']]);
                    foreach ($class_arr as $sub) {
                        $sub_data['class_id'] = $form['id'];
                        $sub_data['sub_id'] = $sub;
                        $sub_model->insertInfo($sub_data);
                    }
                }
                $this->ajaxReturn(200, Yii::t('app', 'Editor success'), $this->navTabId, 1);
            } else {
                $this->ajaxReturn(300, Yii::t('app', 'Editor failed, please try again'));
            }
        } else {
            $this->ajaxReturn(300, Yii::t('app', 'Data already exists'));
        }
    }

    /**
     * 导入页面
     * @return string
     */
    public function actionImport()
    {
        $this->checkAuth($this->id, $this->action->id);
        return $this->render('import');
    }


    /**
     * 获取需要传递到界面的额外数据
     *
     * @return html
     * @author Fee
     */
    public function getPageData($id=0)
    {
        $school_id = Yii::$app->session["school_id"];
        $order_arr['plan_id'] = SORT_DESC;
        //条件
        $where = array();
        $where['school_id'] = $school_id;
        $where['state'] = 0;
        $model = new Timeplans();
        $plan_list = $model->getList($where,'plan_id,plan_name', $order_arr);
        //获取科目
        $subject_list = SysClassSubjects::find()->where(['class_id'=>$id])->asArray()->all();
        $subject_ids = [];
        if ($subject_list) {
            $subject_ids = ArrayHelper::getColumn($subject_list, 'sub_id');
        }
        return [
            'model' => $this->getModel($id),
            'schools' => Schools::getOptions(Yii::$app->session["school_id"]),
            'state' =>$this->getState(),
            'plan_list' =>$plan_list,
            'subject_list' => SysSubjects::get_school_subjects(),
            'subject_ids'=>$subject_ids
        ];
    }

    /**
     * 获取数据
     *
     * @return obj
     * @author Fee
     */
    public function getModel($id=0)
    {
        if($id == 0) {
            return new Classinfo();
        }

        if (($model = Classinfo::findOne($id)) !== null) {
            return $model;
        }

        return $this->ajaxReturn(300,Yii::t('app', 'The record does not exist. Please try again'),$this->navTabId, 1);
    }

    /**
     * 获取状态
     */
    public function getState()
    {
        return [
            '1'=>Yii::t('app/class', 'Kindergarten'),
            '2'=>Yii::t('app/class', 'PrimarySchool'),
            '3'=>Yii::t('app/class', 'JuniorMiddleSchool'),
            '4'=>Yii::t('app/class', 'HighSchool'),
            '5'=>Yii::t('app/class', 'University'),
        ];
    }
    public function getType()
    {
        return [
            Yii::t('app/class', 'Kindergarten')=>1,
            Yii::t('app/class', 'PrimarySchool')=>2,
            Yii::t('app/class', 'JuniorMiddleSchool')=>3,
            Yii::t('app/class', 'HighSchool')=>4,
            Yii::t('app/class', 'University')=>5,
        ];
    }

    /**
     * 复制页面
     * @return string
     */
    public function actionCopy()
    {
        $this->checkAuth($this->id, $this->action->id);
        $id = $_GET['id'];
        return $this->render('copy', ['id'=>$id]);
    }

    /**
     * 复制操作
     */
    public function actionCopies()
    {
        $id = trim($_POST['id']);
        $model = new Classinfo();
        $list = Classinfo::find()->where(['class_id'=>$id])->asArray()->one();
        $subject_list = SysClassSubjects::find()->where(['class_id'=>$id])->asArray()->all();
        $class_name = trim($_POST['class_name']);
        $class_alias = trim($_POST['class_alias']);
        if ($list) {
            //条件
            $where['class_name'] =  $class_name;
            $where['school_id'] =  $list['school_id'];
            $where['year'] =  $list['year'];
            $where['type'] =  $list['type'];
            //班级是否存在
            $count = Classinfo::find()->where($where)->count();
            if ($count>0) {
                $this->ajaxReturn(300, Yii::t('app', 'Data already exists'));
            } else {
                $data['class_name'] = $class_name;
                $data['class_alias'] = $class_alias;
                $data['school_id'] = $list['school_id'];
                $data['year'] = $list['year'];
                $data['type'] = $list['type'];
                $data['plan_id'] = $list['plan_id'];
                $data['remark'] = $list['remark'];
                $data['del_flag'] = $list['del_flag'];
                $result = $model->insertInfo($data);
                if ($result) {
                    if ($subject_list) {
                        $sub_model = new SysClassSubjects();
                        foreach ($subject_list as $sub) {
                            $sub_data['class_id'] = $result;
                            $sub_data['sub_id'] = $sub['sub_id'];
                            $sub_model->insertInfo($sub_data);
                        }
                    }
                    $this->ajaxReturn(200, Yii::t('app', 'Add success'), $this->navTabId, 1);
                } else {
                    $this->ajaxReturn(300, Yii::t('app', 'Add failed, please try again'));
                }
            }
        }
        $this->ajaxReturn(300, Yii::t('app', 'Add failed, please try again'));

    }
    /**
     * Ajax导入excel
     *
     *
     * @return void
     */
    public function actionImports()
    {
        $school_id = Yii::$app->session["school_id"];
        $file_input_name = $_FILES['name'];
        $excel_path = $file_input_name['tmp_name'];
        $file_size_1_m = 1024 * 1024;
        $max_file_size = 2 * $file_size_1_m;//上传文件体积限制
        $file_type = pathinfo($file_input_name['name'], PATHINFO_EXTENSION);
        $type_is_allow = in_array($file_type, array('xlsx', 'xls'));
        //检测文件大小
        $upload_file_size = $file_input_name['size'];
        if ($type_is_allow === false) {
            //类型不对，结束//扩展名不对
            $this->ajaxReturn(300, Yii::t('app/class', 'UploadError1'));
        } elseif ($upload_file_size > $max_file_size) {
            //大小不对，结束
            $this->ajaxReturn(300, Yii::t('app/class', 'UploadError2') . $max_file_size / $file_size_1_m . 'M).');
            return;
        }  else {
            $arr_data = $this->_getDataFromExcel($excel_path);//结果数组 key 1起
            $result = true;
            $list = $this->getType();
            foreach ($arr_data as $key => $value) {
                if ($key == 1) {
                    continue;
                }
                $a = trim($value['A']);
                $b = !is_numeric($value['B']) ? mb_substr(trim($value['B']),0,4,"utf-8") : trim($value['B']);
                $c = empty($list[$value['C']]) ? 0 : trim($list[$value['C']]);
                //判断
                $where['class_name'] =  $a;
                $where['school_id'] =  $school_id;
                $where['year'] =  $b;
                $where['type'] =  $c;
                //班级是否攒在
                $count = Classinfo::find()->where($where)->count();
                if ($count==0) {
                    $data['class_name'] = $a;
                    $data['class_alias'] = trim($value['D']);
                    $data['school_id'] = trim(Yii::$app->session["school_id"]);
                    $data['year'] = $b;
                    //$plan_item = Timeplans::find()->where(['plan_name'=>$value['E']])->select('plan_id')->asArray()->one();
                    $data['type'] = $c;
                    //    $data['plan_id'] = empty($plan_item) ? '0' : $plan_item['plan_id'];
                    //    $data['remark'] = trim($value['F']);
                    $data['del_flag'] = '0';
                    $model = new Classinfo();
                    $result = $model->insertInfo($data);
                }
                
                if ($result) {
                    //科目添加
                    //                    if ($value['D']) {
                    //                        $sub_model = new SysClassSubjects();
                    //                        $cond['sub_name'] = explode(',', $value['D']);
                    //                        $sub_list = Subjects::find()->where($cond)->select('sub_id')->asArray()->all();
                    //                        $sub_ids = [];
                    //                        if ($sub_list) {
                    //                            $sub_ids = ArrayHelper::getColumn($sub_list, 'sub_id');
                    //                        }
                    //                        if (!empty($sub_ids)) {
                    //                            foreach ($sub_ids as $sub) {
                    //                                $sub_data['class_id'] = $result;
                    //                                $sub_data['sub_id'] = $sub;
                    //                                $sub_model->insertInfo($sub_data);
                    //                            }
                    //                        }
                    //                    }
                }

            }
            if ($result) {
                $this->ajaxReturn(200, Yii::t('app', 'Add success'), $this->navTabId, 1);
            } else {
                $this->ajaxReturn(300, Yii::t('app', 'Add failed, please try again'));
            }
        }
    }
    /**
     * 获取excel中的数据存入数组
     *
     * Author zhengyu@iyangpin.com
     *
     * @param string $excel_path excel路径
     *
     * @return array
     */
    private function _getDataFromExcel($excel_path)
    {
        $obj = new PhpExcel();
        $obj_phpexcel = $obj->load($excel_path);
        $arr_data = $obj_phpexcel->getActiveSheet()->toArray(null, true, true, true);
        $obj_phpexcel->disconnectWorksheets();
        unset($obj_phpexcel);

        return $arr_data;
    }
    /**
     * 显示列表页面
     *
     * @return html
     * @author Fee
     */
    public function actionList() {
        $this->checkAuth($this->id, $this->action->id);
        $id = $_GET['id'];//班级id
        $plan_id = $_GET['plan_id'];//方案id
        $plans_model = new Timeplansets();
        $plans_list = $plans_model->getList(['timeplan_id'=>$plan_id], 'num,title', 'num asc');
        $data = [];
        foreach ($plans_list as $key => $value) {
            for ($i=0;$i<=7;$i++) {
                $data[$key][$i]['x']=$i;
                $data[$key][$i]['y']=$value['num'];
                if ($i==0) {
                    $data[$key][$i]['title'] = $value['title'];
                } else {
                    $cond['class_id'] = $id;
                    $cond['day'] = $i;
                    $cond['num']= $value['num'];
                    $item = Syllabus::find()->select('*')->where($cond)->asArray()->one();
                    if ($item) {
                        $list = SysSubjects::find()->select('sub_name,alias,parent_id')
                                                    ->where(['sub_id'=>$item['subject_id']])
                                                    ->with(['parent'])
                                                    ->asArray()
                                                    ->one();
                        if ($list) {
                            if(empty($list['parent']['alias'])){
                                $data[$key][$i]['title'] = $list['parent']['sub_name'];
                            } else {
                                $data[$key][$i]['title'] = $list['parent']['alias'];
                            }
                        }   else {
                            $data[$key][$i]['title'] = "--";
                        }
                    }   else {
                        $data[$key][$i]['title'] = "--";
                    }
                }

            }
        }
        return $this->render('list',[
            'list' => $data,
            'id' =>$id
        ]);
    }

    /**
     * 排课
     * @return string
     */
    public function actionSubject()
    {
        $this->checkAuth($this->id, $this->action->id);
        $cond['class_id'] = $_GET['id'];
        $cond['day'] = $_GET['day'];
        $cond['num']= $_GET['num'];
        $item = Syllabus::find()->where($cond)->asArray()->one();
        $list = SysSubjects::get_class_subjects($cond['class_id'], 1);
        return $this->render('subject', ['list'=>$list,'item'=>$item]);
    }

    /**
     * 排课操作(增加 修改)
     */
    public function actionSave()
    {

        $this->checkAuth($this->id, $this->action->id);
        $form = Yii::$app->request->post();
        $url =  "classsyllabus";
        $cond['class_id'] = $form['id'];
        $cond['day'] = $form['day'];
        $cond['num']= $form['num'];
        $item = Syllabus::find()->select('*')->where($cond)->asArray()->one();
        $model = new Syllabus();
        if ($item) {
            $result = $model->updateInfo(['subject_id'=>$form['subject_id']],['syllabus_id'=>$item['syllabus_id']]);
            if ($result) {
                $this->ajaxReturn(200, Yii::t('app', 'Add success'), $url, 1);
            } else {
                $this->ajaxReturn(300, Yii::t('app', 'Add failed, please try again'));
            }
        }
        $data['class_id'] = $form['id'];
        $data['day'] = $form['day'];
        $data['num']= $form['num'];
        $data['subject_id'] = $form['subject_id'];
        $result = $model->insertInfo($data);
        if ($result) {
            $this->ajaxReturn(200, Yii::t('app', 'Add success'), $url, 1);

        } else {
            $this->ajaxReturn(300, Yii::t('app', 'Add failed, please try again'));
        }
    }
}